package com.jianguozh.difs.support.api.ops;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import com.jianguozh.difs.common.bean.R;
import com.jianguozh.difs.framework.base.BaseController;
import com.jianguozh.difs.framework.utils.SpringUtils;
import com.jianguozh.difs.support.api.ops.dto.ConfigDto;
import com.jianguozh.difs.support.service.base.entity.Config;
import com.jianguozh.difs.support.service.base.service.IConfigService;
import com.jianguozh.difs.support.service.component.setting.Setting;
import com.jianguozh.difs.support.service.constant.enums.ConfigTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 配置控制器
 *
 * @author hanrs
 * @email 4076130@qq.com
 * @since 2022/7/12 9:47
 */
@RestController
@RequestMapping("/config")
public class ConfigController extends BaseController {

    @Autowired
    IConfigService configService;

    @GetMapping("/{type}")
    public R<Setting> getByType(@PathVariable ConfigTypeEnum type) {
        Config config = configService.getByType(type);
        if (ObjectUtil.isNull(config)) {
            return success();
        } else {
            return success(config.getSetting());
        }
    }

    /**
     * 保存
     */
    @PutMapping("")
    public R<Config> save(@RequestBody ConfigDto configDto) {
        ConfigTypeEnum configTypeEnum = configDto.getConfigTypeEnum();
        Map<String, Object> settingMap = configDto.getSetting();
        Setting setting = configService.parseSetting(configTypeEnum, settingMap);

        Config config = configService.getByType(configTypeEnum);
        if (ObjectUtil.isNull(config)) {
            config = new Config();
            config.setConfigType(configTypeEnum);
        }
        config.setDescription(configDto.getDescription());
        config.setSetting(setting);
        boolean result = configService.saveOrUpdate(config);
        if (result) {  //配置修改成功一般有后置事件
            ApplicationEvent event = ReflectUtil.newInstance(configTypeEnum.getEventClass(), setting);
            SpringUtils.getApplicationContext().publishEvent(event);
        }
        return result ? success(config) : failed("操作失败.");
    }

}
